package com.pinion.controller.statistics;

import com.base.config.Constant;
import com.base.config.Dates;
import com.base.model.LoginModel;
import com.base.model.authority.T_User;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.pinion.json.BrandTypeStatistics;
import com.pinion.model.T_Brand;
import com.pinion.model.T_Goods_Type;
import com.pinion.model.T_Order_Item;
import com.pinion.util.BusinessConstant;
import com.zh_new.annotation.RouteBind;
import com.zh_new.controller.BaseController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 分品牌类型统计
 */
@RouteBind(path = "/Main/BrandTypeStatistics", viewPath = "/Statistics")
public class BrandTypeStatisticsController extends BaseController {

    private static final Logger log = Logger.getLogger(BrandTypeStatisticsController.class);

    public void main() {
        LoginModel loginModel = (LoginModel) getSessionAttr("loginModel");
        String roleIds = loginModel.getRoleIds();
        //超级管理员or系统管理员
        if (roleIds.contains("_" + Constant.SUPER_USER + ",") || roleIds.contains("_" + Constant.ADMIN_USER + ",")) {
            manageStatistic();
        } else if (roleIds.contains("_" + Constant.SELLER_USER + ",")) {    //销售员
            sellStatistic(loginModel.getUserStaffId());
        } else {
            oriStatistic();
        }
    }

    //管理员统计页
    public void manageStatistic() {
        String selectStart = StrKit.isBlank(getPara("selectStart")) ? new SimpleDateFormat("yyyy").format(new Date()) + "-01-01" : getPara("selectStart");
        String selectEnd = StrKit.isBlank(getPara("selectEnd")) ? new SimpleDateFormat("yyyy-MM-dd").format(new Date()) : getPara("selectEnd");
        //分类方式:a.按照品牌分类(BY_BRAND),b.按照销售员分类(BY_SELLER),c.按每月的总销售额(BY_MONTH_SALES)
        String classifyOpt = StrKit.isBlank(getPara("classifyOpt")) ? "BY_BRAND" : getPara("classifyOpt");
        String brandNumber = getPara("brandNumber");        //品牌编号
        String sellerNumber = getPara("sellerNumber");      //员工编号
        String selectYear = StrKit.isBlank(getPara("selectYear")) ? new SimpleDateFormat("yyyy").format(new Date()) : getPara("selectYear");          //按月统计此年份
        List<Record> list = null;
        //默认为BY_BRAND
        if ("BY_SELLER".equals(classifyOpt)) {
            list = statisticBySeller(selectStart, selectEnd, sellerNumber);
        } else if ("BY_BRAND".equals(classifyOpt)) {
            list = statisticByBrand(selectStart, selectEnd, brandNumber);
        } else if ("BY_MONTH_SALES".equals(classifyOpt)) {
            list = statisticByMonthSales(selectYear);
        } else {
            renderJson("{\"statusCode\":\"300\", " +
                    "\"message\":\"存入参数出错[classifyOpt=" + classifyOpt + "]，数据读取失败！\"}");
            return;
        }
        try {
            setAttr("classifyOpt", classifyOpt);
            setAttr("sellerList", T_User.dao.getListByRole(Constant.SELLER_USER)); //销售员列表
            setAttr("brandList", T_Brand.dao.list());
            setAttr("list", list);
            setAttr("selectStart", selectStart);
            setAttr("selectEnd", selectEnd);
            setAttr("brandNumber", brandNumber);
            setAttr("sellerNumber", sellerNumber);
            setAttr("selectYear", selectYear);
            render("manageStatistic.jsp");
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            renderJson("{\"statusCode\":\"300\", " +
                    "\"message\":\"服务器存在错误，数据读取失败！\"}");
        }
    }

    //销售员统计页
    //String sellerNumber:员工编号
    public void sellStatistic(String sellerNumber) {
        String selectStart = StrKit.isBlank(getPara("selectStart")) ? new SimpleDateFormat("yyyy").format(new Date()) + "-01-01" : getPara("selectStart");
        String selectEnd = StrKit.isBlank(getPara("selectEnd")) ? new SimpleDateFormat("yyyy-MM-dd").format(new Date()) : getPara("selectEnd");
        //默认为BY_SELLER
        List<Record> list = statisticBySeller(selectStart, selectEnd, sellerNumber);
        try {
            setAttr("list", list);
            setAttr("selectStart", selectStart);
            setAttr("selectEnd", selectEnd);
            setAttr("sellerNumber", sellerNumber);
            render("sellStatistic.jsp");
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            renderJson("{\"statusCode\":\"300\", " +
                    "\"message\":\"服务器存在错误，数据读取失败！\"}");
        }
    }

    /*按品牌分类统计*/
    private List<Record> statisticByBrand(String selectStart, String selectEnd, String brandNumber) {
        String groupSql = " GROUP BY b.brand_number";

        String sql = " SELECT b.brand_name as brand_name,"
                + " sum(b.transaction_value) as total_sales,"
                + " sum((b.transaction_value-b.commission) * b.goods_count) as total_commission,"
                + " sum(b.goods_count) as total_sales_volume"
                + " FROM t_order a"
                + " LEFT JOIN t_order_item b ON a.id=b.order_id"
                + " LEFT JOIN t_goods c ON b.goods_number = c.number"
                + " WHERE a.update_time >= ? AND a.update_time <= ?"
                + " AND a.status = " + Constant.ORDER_STATUS_FINISHED;   //已完成状态: [Constant.ORDER_STATUS_FINISHED = 5]

        List<Record> result = null;
        if (null != brandNumber && 0 != brandNumber.trim().length()) {
            sql += " AND b.brand_number = ?";
            sql += groupSql;
            result = Db.find(sql, selectStart, selectEnd, brandNumber.trim());
        } else {
            sql += groupSql;
            result = Db.find(sql, selectStart, selectEnd);
        }
        return result;
    }

    /*按销售员分类统计*/
    private List<Record> statisticBySeller(String selectStart, String selectEnd, String sellerNumber) {
        String groupSql = " GROUP BY a.salesman_staff_id";

        String sql = " SELECT a.salesman_name as salesman_name,"
                + " sum(b.transaction_value) as total_sales,"
                + " sum((b.transaction_value-b.commission) * b.goods_count) as total_commission"
                + " FROM t_order a"
                + " LEFT JOIN t_order_item b ON a.id=b.order_id"
                + " LEFT JOIN t_goods c ON b.goods_number = c.number"
                + " WHERE a.update_time >= ? AND a.update_time <= ?"
                + " AND a.status = " + Constant.ORDER_STATUS_FINISHED;   //已完成状态: [Constant.ORDER_STATUS_FINISHED = 5]

        List<Record> result = null;
        if (null != sellerNumber && 0 != sellerNumber.trim().length()) {
            sql += " AND a.salesman_staff_id = ?";
            sql += groupSql;
            result = Db.find(sql, selectStart, selectEnd, sellerNumber);
        } else {
            sql += groupSql;
            result = Db.find(sql, selectStart, selectEnd);
        }
        return result;
    }

    /*按每月的总销售额分类统计*/
    private List<Record> statisticByMonthSales(String selectYear) {
        String startDate;
        String endDate;
        int endMonth = Integer.valueOf(new SimpleDateFormat("MM").format(new Date()));
        List<Record> resultList = new ArrayList<Record>();

        for (int i = 1; i <= endMonth; i++) {
            startDate = String.format("%s-%02d-01", selectYear, i);
            endDate = (12 == i) ? String.format("%d-01-01", Integer.valueOf(selectYear) + 1) : String.format("%s-%02d-01", selectYear, i + 1);
            System.out.println("--->[" + startDate + "," + endDate + "]");
            String sql = " SELECT ? as month_idx,"
                    + " sum(b.transaction_value) as total_sales,"
                    + " sum((b.transaction_value-b.commission) * b.goods_count) as total_commission,"
                    + " sum(b.goods_count) as total_sales_volume"
                    + " FROM t_order a"
                    + " LEFT JOIN t_order_item b ON a.id=b.order_id"
                    + " LEFT JOIN t_goods c ON b.goods_number = c.number"
                    + " WHERE a.update_time >= ? AND a.update_time <= ?"
                    + " AND a.status = " + Constant.ORDER_STATUS_FINISHED;   //已完成状态: [Constant.ORDER_STATUS_FINISHED = 5]

            List<Record> result = Db.find(sql, i, startDate, endDate);
            if (null != result) {
                resultList.add(result.get(0));
            } else {
                resultList.add(null);
            }
        }
        return resultList;
    }


    //原统计页
    public void oriStatistic() {
        String year = StrKit.isBlank(getPara("year")) ? new SimpleDateFormat("yyyy").format(new Date()) : getPara("year");
        Integer type = null == getParaToInt("type") ? BusinessConstant.YEAR_TYPE : getParaToInt("type");
        Integer brandId = getParaToInt("brandId");
        Integer goodsType = getParaToInt("goodsType");
        String selectEnd = null;
        String selectStart = null;

        selectStart = year;
        if (type == BusinessConstant.YEAR_TYPE) {
            selectStart = selectStart + "-01";
            selectEnd = String.valueOf(Integer.valueOf(year) + 1) + "-01";
        } else if (type == BusinessConstant.QUARTER_FIRST_TYPE) {
            selectStart = year + "-" + BusinessConstant.QUARTER_FIRST;
            selectEnd = year + "-" + BusinessConstant.QUARTER_SECOND;
        } else if (type == BusinessConstant.QUARTER_SECOND_TYPE) {
            selectStart = year + "-" + BusinessConstant.QUARTER_SECOND;
            selectEnd = year + "-" + BusinessConstant.QUARTER_THIRD;
        } else if (type == BusinessConstant.QUARTER_THIRD_TYPE) {
            selectStart = year + "-" + BusinessConstant.QUARTER_THIRD;
            selectEnd = year + "-" + BusinessConstant.QUARTER_FOURTH;
        } else if (type == BusinessConstant.QUARTER_FOURTH_TYPE) {
            selectStart = year + "-" + BusinessConstant.QUARTER_FOURTH;
            selectEnd = String.valueOf((Integer.valueOf(year) + 1)) + "-" + BusinessConstant.QUARTER_FIRST;
        } else {
            String month = String.valueOf(type);
            if (month.length() == 1) {
                month = "0" + month;
            }
            selectStart = year + "-" + month;
            selectEnd = new SimpleDateFormat(Constant.DATE_PATTERN_MONTH).format(new Date(Dates.parse(selectStart).getTime() + Dates.getDaysOfMonth(selectStart) * Constant.INTERVAL_DAY));
        }
        List<BrandTypeStatistics> list = count(selectStart, selectEnd, brandId, goodsType);
        try {
            setAttr("brandList", T_Brand.dao.list());
            setAttr("goodsTypeList", T_Goods_Type.dao.list());
            setAttr("list", list);
            setAttr("year", year);
            setAttr("type", type);
            setAttr("brandId", brandId);
            setAttr("goodsType", goodsType);
            render("brandTypeStatistics.jsp");
        } catch (Exception e) {
            log.error("服务器存在错误，数据读取失败！", e);
            renderJson("{\"statusCode\":\"300\", " +
                    "\"message\":\"服务器存在错误，数据读取失败！\"}");
        }
    }


    public List<BrandTypeStatistics> count(String date_start, String date_end, Integer brandId, Integer goodsType) {
        List<BrandTypeStatistics> list = new ArrayList<BrandTypeStatistics>();
        int start = Integer.valueOf(date_start.substring(5));
        int end = Integer.valueOf(date_end.substring(5));
        if ((end - start) == 1 || (end - start) == -11) {
            BrandTypeStatistics o = new BrandTypeStatistics();
            //销售额
            double sales = T_Order_Item.dao.count(date_start, date_end, brandId, goodsType, BusinessConstant.REAL_PAY_PRICE);
            //总原价
            double price = T_Order_Item.dao.count(date_start, date_end, brandId, goodsType, BusinessConstant.ORIGINAL_PRICE);
            //销售量
            long total = T_Order_Item.dao.countQuantity(date_start, date_end, brandId, goodsType);
            o.setMonth(date_start);
            o.setTotalSales(sales);
            o.setTotalPrice(price);
            o.setTotal(total);
            list.add(o);
        } else {
            int months = end - start;
            months = months == -9 ? 3 : months;
            months = months == 0 ? 12 : months;
            double salesCount = 0;
            double priceCount = 0;
            long totalCount = 0;
            for (int i = 0; i < months; i++) {
                date_end = new SimpleDateFormat(Constant.DATE_PATTERN_MONTH).format(new Date(Dates.parse(date_start).getTime() + Dates.getDaysOfMonth(date_start) * Constant.INTERVAL_DAY));
                BrandTypeStatistics o = new BrandTypeStatistics();
                //销售额
                double sales = T_Order_Item.dao.count(date_start, date_end, brandId, goodsType, BusinessConstant.REAL_PAY_PRICE);
                //总原价
                double price = T_Order_Item.dao.count(date_start, date_end, brandId, goodsType, BusinessConstant.ORIGINAL_PRICE);
                //销售量
                long total = T_Order_Item.dao.countQuantity(date_start, date_end, brandId, goodsType);
                salesCount += sales;
                priceCount += price;
                totalCount += total;
                o.setMonth(date_start);
                o.setTotalSales(sales);
                o.setTotalPrice(price);
                o.setTotal(total);
                list.add(o);
                date_start = date_end;
            }
            BrandTypeStatistics o = new BrandTypeStatistics();
            o.setMonth("合计");
            o.setTotalSales(salesCount);
            o.setTotalPrice(priceCount);
            o.setTotal(totalCount);
            list.add(o);
        }
        return list;
    }
}
